package com.kgar.util;

import cn.hutool.core.util.StrUtil;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.InputStream;

@Slf4j
@Component
@Lazy
public class AliOSSUtil {


    @Value("${aliyun.oss.endpoint}")
    private  String endpoint ;

    @Value("${aliyun.oss.bucketName}")
    private  String bucketName ;

    @Resource
    private  OSS ossClient;


    public String uploadFile(InputStream fileInputStream, String saveFileName) {

        ossClient.putObject(bucketName,saveFileName, fileInputStream);
        return StrUtil.format("https://{}.{}/",bucketName,endpoint)+saveFileName;

    }
    public void deleteFile(String fileName)  {
        //获取文件真实名字
        String realFileName = fileName.substring(StrUtil.format("https://{}.{}.aliyuncs.com/",bucketName,endpoint).length());

        try {
            ossClient.deleteObject(bucketName, realFileName);
            log.info("已删除文件: {}",fileName);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        }

    }

}
